package com.fsi.client.util;

import java.util.Date;

import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.ListBox;

public class MyDate extends HorizontalPanel {
	public static final String[] months = { "January", "February", "March",
			"April", "May", "June", "July", "August", "September", "October",
			"November", "December" };
	private static final int AGEOFFSET = 18;
	private final Date currentDate;

	private final ListBox day;
	private final MyList month;
	private final ListBox year;

	public MyDate() {
		currentDate = new Date();
		day = new ListBox();
		month = new MyList(months);
		year = new ListBox();

		loadDays();
		loadYears();

		this.add(day);
		this.add(month);
		this.add(year);
	}

	@SuppressWarnings("deprecation")
	private void loadYears() {
		int currentYear = 1900 + currentDate.getYear();
		for (int i = currentYear - AGEOFFSET; i >= currentYear - 100; i--) {
			year.addItem(Integer.toString(i));
		}
	}

	private void loadDays() {
		for (int i = 1; i <= 31; i++) {
			day.addItem(Integer.toString(i));
		}
	}

	@SuppressWarnings("deprecation")
	public Date getDate() {
		Date d = null;
		int y = currentDate.getYear() - year.getSelectedIndex() - AGEOFFSET;
		try {
			// d = new Date(0, 0, 0);
			d = new Date(y, month.getSelectedIndex() + 1, day
					.getSelectedIndex() + 1);
		} catch (Exception e) {
			Window.alert("Invalid date specified");
		}
		return d;
	}

	@SuppressWarnings("deprecation")
	public void setDate(Date date) {
		this.day.setItemSelected(date.getDate() - 1, true);
		this.month.setItemSelected(date.getMonth() - 1, true);
		this.year.setItemSelected(currentDate.getYear() - date.getYear()
				- AGEOFFSET, true);
	}

}
